<?php
// +----------------------------------------------------------------------
// |ZBPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.benbenwangluo.com
// +----------------------------------------------------------------------
// | Author 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 中犇软件 技术六部 出品
// +----------------------------------------------------------------------

namespace app\customer\controller;
use app\customer\model\Customer;


/**
 * 客服端聊天界面处理
 * @package app\customer\controller
 */
class Message extends \think\Controller
{
    
    protected  $user_id = null;
    protected function initialize()
    {          
        config('app.dispatch_error_tmpl',  'customer@home/public/error');    
        $this->user_id = session("service_user_id");
        if(!$this->user_id ){
            $this->redirect(url("/customer/login/index"));
        }
    }
    /**
     * 客服列表
     * @author 晓风<215628355@qq.com>
     * @return mixed
     */
    public function index()
    {
        //查询我在多店铺中的角色        
        $stores = Customer::getStores($this->user_id );
        if(!$stores || count($stores) < 1){
            $this->error("服务异常，出现不可预见的错误,请重新登录",url('login/signout'));
        }       
        
        $userSig = \app\customer\model\Chat::getUserSig($this->user_id);
        //$userList = \app\customer\model\Session::getServerSessionList($this->user_id);
       // $offUserList = \app\customer\model\Session::getServerSessionList(0);
        $this->assign("userId",$this->user_id);
        $this->assign("stores",$stores);
        $this->assign("serviceStatus",Customer::$status);
       // $this->assign("userList",$userList);
       // $this->assign("offUserList",$offUserList);
        $this->assign("userSig",$userSig);
        $this->assign("upToken", $this->request->token('osstoken'));
        return $this->fetch($this->request->isMobile() ? 'mobile': 'index');
    }
    
    public function get_user_messages(){
        $user_id = input("user_id/d",0);
        $store_id= input("store_id/d",0);
        if(!$user_id || !$store_id){
            $this->result([], 0, "参数错误", "json");
        }
        $msgid = input("msgid","");
        
        $store = \app\customer\model\Shop::field("store_name as user_nickname,store_logo as head_img")->where("store_id",$store_id)->find();
        if(!$store){
            $this->result([], 0, "店铺不存在", "json");
        }  
        $user = \app\user\model\User::field("user_nickname,head_img")->where("id",$user_id)->find();        
        if(!$user){
            $this->result([], 0, "会员不存在", "json");
        }  
    
        $store['head_img'] = get_file_url($store["head_img"]);
        $user['head_img'] = get_file_url($user["head_img"]);
        
        $userList = \app\customer\model\Chat::getUserStoreMsgList($user_id,$store_id,$this->user_id , $msgid);
        $info = [];
        
        foreach($userList as $item){
            $member = $item["form_type"]  == 2 ?  $store :$user;     
            $item['head_img'] = $member['head_img'];      
            $item['nickname'] =  $member['user_nickname'];                  
            $info[] = $item;
        }
        \app\customer\model\Session::clearSessionNoRead($this->user_id ,$store_id,2);
        $this->result($info, 1, "ok", "json");
    }
    
    public function check_service_user(){
        $user_id = input("user_id/d",0);
        $store_id= input("store_id/d",0);
        $type = input("type/d",0);
        $content = input("content","");
        $session_title= input("session_title","");
        if(!$user_id || !$store_id || !$content){
            $this->result([], 0, "参数错误", "json");
        }
        $toUser = \app\user\model\User::field("user_nickname,head_img")->where("id",$user_id)->find();        
        if(!$toUser){
            $this->result([], 0, "会员不存在", "json");
        }  
        \think\Db::startTrans();
        try{            
            $data['session_title'] = $data['session_title'] ??  "";
            $result = \app\customer\model\Chat::addServiceMessageInfo($store_id,$this->user_id, $user_id, $type,$content , $session_title);
            \think\Db::commit();            
        }catch(\Exception $e){
            \think\Db::rollback();          
            $this->result([], 0, $e->getMessage(), "json");
        }            
        $message = [
            "msgid"=> $result['msgid'],    
            "type"=> $result['type'],      
            "content"=> $result['content'],   
            "user_id"=>$this->user_id,
            "store_id"=> $store_id,          
            "service_user_id"=> $result['service_user_id'],
            "nickname"=>  $result['store_name'],    
            "head_img"=>  get_file_url($result["store_logo"]),              
            "form_type"=>$result['form_type'],   
            "create_time"=>date("Y-m-d H:i:s",$result["create_time"]),
            "session_title"=>$result['session_title'],
            "store_name"=>  $result['store_name'],    
            "store_logo"=>  get_file_url($result["store_logo"]),   
        ];
        $this->result($message, 1, "ok", "json");
    }

    public function get_user_info($user_id,$store_id){        
        $user = \app\user\model\User::field("id,mobile,user_nickname,head_img,last_login_ip,last_login_time")->where("id",$user_id)->find();        
        if(!$user){
            $this->error( "会员不存在");
        }          
        if($this->request->isAjax()){
            $this->result($user, 1, "ok", "json");
        }
        $user["last_login_time"] = format_time($user["last_login_time"]);
        $this->assign("user",$user);
        return $this->fetch();
    }
    
    public function get_order_litst($user_id,$store_id){        
        $orders = \app\common\model\Order::where("user_id",$user_id)->field("order_sn,status,create_time,payable_money")->order("create_time desc")->limit(10)->select();        
        foreach ($orders as &$item){
            $item['status_at'] =  \app\common\model\Order::$order_status[$item['status']];
            $goods = \app\order\model\OrderGoods::where("order_sn",$item["order_sn"])->field("goods_id,sku_id,goods_name,sku_name,goods_thumb,goods_money,num")->select();
            foreach($goods as &$g){
                $g["goods_thumb"] = get_thumb( $g["goods_thumb"]);
            }
            $item["goods"] = $goods;
        }
        $this->result($orders, 1, "ok", "json");
    }
    
    public function get_goods_litst($user_id,$store_id){        
        $goods = \app\goods\model\Goods::view("goods","id,name,thumb,shop_price,sales_sum,stock")
                ->view("user_collection",'create_time,sku_id',"goods.id = user_collection.collect_id and user_collection.type = 3 and user_collection.status = 1")
                ->where("goods.status",1)                
                ->where("goods.is_sale",1)
                ->where("goods.is_delete",0)
                ->where("user_collection.user_id",$user_id)
                ->order("user_collection.create_time desc")
                ->limit(10)
                ->select();    
        
        foreach ($goods as &$g){       
            $g["thumb"] = get_thumb( $g["thumb"]);          
        }
        $this->result($goods, 1, "ok", "json");
    }
    
    
    public function set_store_status(){
        $store_id= input("store_id/d",0);
        $status = input("status/d",0);        
        Customer::where("member_id",$this->user_id)->where("store_id",$store_id)->setField("status",$status);
        $this->result([], 1, "ok", "json");
    }
    /**
     * 获取会话列表
     * @author 晓风<215628355@qq.com>
     */
    public function get_users_list(){        
        $user_id = input("user_id/d",0);
        $size = 100;
        $stores = Customer::where("member_id",$this->user_id )->column("store_id");
        $userList = \app\customer\model\Session::getServerSessionList($user_id ,$stores, $size)->each(function($item){
            $item["head_img"] = get_file_url($item["head_img"]);
            $item["store_logo"] = get_file_url($item["store_logo"]);        
            $item["update_time_at"] =  \app\customer\model\Session::chatDate($item->getData("update_time"));
            return $item;
        });
        $this->result($userList, 1, "ok", "json");
    }   
      /**
     * 删除会话
     * @author 晓风<215628355@qq.com>
     */
    public  function del_store_session(){
        $user_id = input("user_id/d",0);
        $store_id = input("store_id/d",0);
        if(!$user_id || !$store_id){
            $this->result([], 0, "参数错误", "json");
        }
        \app\customer\model\Session::where("store_id",$store_id)->where("user_id",$user_id)->where("service_user_id",$this->user_id)->update([
            "service_delete"=>1,
            "service_user_id"=>0
        ]);
        $this->result([],1, "已删除会话", "json");
    }
}